package com.tianqu.tms.www.user.controller;

import java.util.List;

import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TmsController;
import com.tianqu.tms.core.base.TxController;
import com.tianqu.tms.core.base.UserContext;
import com.tianqu.tms.core.exception.TmsException;
import com.tianqu.tms.core.exception.TransactionException;
import com.tianqu.tms.core.util.TmsConstants;
import com.tianqu.tms.entity.UserAuth;
import com.tianqu.tms.entity.UserRole;
import com.tianqu.tms.www.user.viewhelper.UserDetailViewHelper;

/**
 * @author zhangxueliang 修改权限确认controller
 */
public class UserRoleUpdateResultController extends TmsController {
	private Logger logger = Logger
			.getLogger(UserRoleUpdateResultController.class);

	@SuppressWarnings("unchecked")
	@Override
	public void execute(UserContext uc) throws Exception {
		logger.debug(this.getClass().getName() + "#execute was called.");

		TxController controller = TxController.getTxController();

		// 添加事务提交异常捕获
		try {
			controller.begin();
			UserAuth userAuth = UserAuth.getInstance();
			UserDetailViewHelper userDetailViewHelper = new UserDetailViewHelper();
			UserDetailViewHelper userViewHelper = new UserDetailViewHelper();
			userDetailViewHelper = (UserDetailViewHelper) uc
					.getAttribute("view");
			userViewHelper = (UserDetailViewHelper) uc
					.getAttribute(TmsConstants.VIEWHELP);

			List rList = userViewHelper.getrList();

			// int ucId = Integer.parseInt(userDetailViewHelper.getUcId());
			int id = Integer.parseInt(userDetailViewHelper.getId());

			userAuth.delUserAuthInfo(id);// 删除该用户所有的

			for (int i = 0; i < rList.size(); i++) {
				UserRole userRole = (UserRole) rList.get(i);
				if (userRole.getChecked() == 1) {
					userAuth.insertUserAuthInfo(id, userRole.getRole());
				}
			}

			logger
					.debug(this.getClass().getName()
							+ "#doAction was completed.");
			controller.commit();
		} catch (Exception e) {
			try {
				controller.rollback();
			} catch (TransactionException e1) {
				throw new TmsException(TmsException.DB_TXCRROR, e1);
			}
			// 系统异常
			if (e instanceof TmsException) {
				throw e;
			}
			throw new TmsException(TmsException.DB_TXCRROR, e);
		}

	}

}
